{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 加载数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pandas import DataFrame\n",
    "from pandas import concat\n",
    "\n",
    "def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):\n",
    "\t\"\"\"\n",
    "\tFrame a time series as a supervised learning dataset.\n",
    "\tArguments:\n",
    "\t\tdata: Sequence of observations as a list or NumPy array.\n",
    "\t\tn_in: Number of lag observations as input (X).\n",
    "\t\tn_out: Number of observations as output (y).\n",
    "\t\tdropnan: Boolean whether or not to drop rows with NaN values.\n",
    "\tReturns:\n",
    "\t\tPandas DataFrame of series framed for supervised learning.\n",
    "\t\"\"\"\n",
    "\tn_vars = 1 if type(data) is list else data.shape[1]\n",
    "\tdf = DataFrame(data)\n",
    "\tcols, names = list(), list()\n",
    "\t# input sequence (t-n, ... t-1)\n",
    "\tfor i in range(n_in, 0, -1):\n",
    "\t\tcols.append(df.shift(i))\n",
    "\t\tnames += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]\n",
    "\t# forecast sequence (t, t+1, ... t+n)\n",
    "\tfor i in range(0, n_out):\n",
    "\t\tcols.append(df.shift(-i))\n",
    "\t\tif i == 0:\n",
    "\t\t\tnames += [('var%d(t)' % (j+1)) for j in range(n_vars)]\n",
    "\t\telse:\n",
    "\t\t\tnames += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]\n",
    "\t# put it all together\n",
    "\tagg = concat(cols, axis=1)\n",
    "\tagg.columns = names\n",
    "\t# drop rows with NaN values\n",
    "\tif dropnan:\n",
    "\t\tagg.dropna(inplace=True)\n",
    "\treturn agg"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
      "   var1(t-4)  var1(t-3)  var1(t-2)  var1(t-1)  var1(t)  var1(t+1)  var1(t+2)\n",
      "4        0.0        1.0        2.0        3.0        4        5.0        6.0\n",
      "5        1.0        2.0        3.0        4.0        5        6.0        7.0\n",
      "6        2.0        3.0        4.0        5.0        6        7.0        8.0\n",
      "7        3.0        4.0        5.0        6.0        7        8.0        9.0\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "(4, 7)\n"
     ]
    }
   ],
   "source": [
    "values = [x for x in range(10)]\n",
    "print(values)\n",
    "input_column = 4\n",
    "predict_column = 3\n",
    "data = series_to_supervised(values, input_column, predict_column)\n",
    "print(data)\n",
    "print(type(data))\n",
    "print(data.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   var1(t-4)  var1(t-3)  var1(t-2)  var1(t-1)\n",
      "4        0.0        1.0        2.0        3.0\n",
      "5        1.0        2.0        3.0        4.0\n",
      "6        2.0        3.0        4.0        5.0\n",
      "7        3.0        4.0        5.0        6.0\n",
      "=============================\n",
      "   var1(t)  var1(t+1)  var1(t+2)\n",
      "4        4        5.0        6.0\n",
      "5        5        6.0        7.0\n",
      "6        6        7.0        8.0\n",
      "7        7        8.0        9.0\n",
      "[[[0.]\n",
      "  [1.]\n",
      "  [2.]\n",
      "  [3.]]\n",
      "\n",
      " [[1.]\n",
      "  [2.]\n",
      "  [3.]\n",
      "  [4.]]\n",
      "\n",
      " [[2.]\n",
      "  [3.]\n",
      "  [4.]\n",
      "  [5.]]\n",
      "\n",
      " [[3.]\n",
      "  [4.]\n",
      "  [5.]\n",
      "  [6.]]]\n",
      "(4, 4, 1)\n",
      "(4, 3, 1)\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "处理数据\n",
    "'''\n",
    "train_x = data.iloc[:,:-predict_column]#除了最后一列不要,代码还可以更加完善可读性高\n",
    "train_y = data.iloc[:,-predict_column:]\n",
    "print(train_x)\n",
    "print(\"=============================\")\n",
    "print(train_y)\n",
    "train_x = train_x.values#values才能reshape，否则AttributeError: 'DataFrame' object has no attribute 'reshape'\n",
    "train_y = train_y.values\n",
    "# train_x = train_x.reshape((train_x.shape[0], 1, train_x.shape[1]))#[hang,1,column]适合一个时间步多个变量也就是多个feature的打法\n",
    "train_x = train_x.reshape(train_x.shape[0], train_x.shape[1], 1)#适合多个时间步单个变量也就是单个feature的打法\n",
    "train_y = train_y.reshape((train_y.shape[0],train_y.shape[1], 1))#适合\n",
    "\n",
    "print(train_x)\n",
    "print(train_x.shape)\n",
    "print(train_y.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n",
      "C:\\Users\\forwhat\\anaconda3\\envs\\pytorch-gpu\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "C:\\Users\\forwhat\\anaconda3\\envs\\pytorch-gpu\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "C:\\Users\\forwhat\\anaconda3\\envs\\pytorch-gpu\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "C:\\Users\\forwhat\\anaconda3\\envs\\pytorch-gpu\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:529: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "C:\\Users\\forwhat\\anaconda3\\envs\\pytorch-gpu\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:530: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "C:\\Users\\forwhat\\anaconda3\\envs\\pytorch-gpu\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:535: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n"
     ]
    }
   ],
   "source": [
    "import numpy\n",
    "import matplotlib.pyplot as plt\n",
    "from keras.models import Sequential\n",
    "from keras.layers import Dense\n",
    "from keras.layers import LSTM\n",
    "import  pandas as pd\n",
    "import  os\n",
    "from keras.models import Sequential, load_model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def mkdir(path):\n",
    "    # 引入模块\n",
    "    import os\n",
    " \n",
    "    # 去除首位空格\n",
    "    path=path.strip()\n",
    "    # 去除尾部 \\ 符号\n",
    "    path=path.rstrip(\"\\\\\")\n",
    " \n",
    "    # 判断路径是否存在\n",
    "    # 存在     True\n",
    "    # 不存在   False\n",
    "    isExists=os.path.exists(path)\n",
    " \n",
    "    # 判断结果\n",
    "    if not isExists:\n",
    "        # 如果不存在则创建目录\n",
    "        # 创建目录操作函数\n",
    "        os.makedirs(path) \n",
    " \n",
    "        print (path+' 创建成功')\n",
    "        return True\n",
    "    else:\n",
    "        # 如果目录存在则不创建，并提示目录已存在\n",
    "        print (path+' 目录已存在')\n",
    "        return False\n",
    " "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From C:\\Users\\forwhat\\anaconda3\\envs\\pytorch-gpu\\lib\\site-packages\\tensorflow\\python\\framework\\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Colocations handled automatically by placer.\n",
      "_________________________________________________________________\n",
      "Layer (type)                 Output Shape              Param #   \n",
      "=================================================================\n",
      "lstm_1 (LSTM)                (None, 4, 128)            66560     \n",
      "_________________________________________________________________\n",
      "time_distributed_1 (TimeDist (None, 4, 1)              129       \n",
      "=================================================================\n",
      "Total params: 66,689\n",
      "Trainable params: 66,689\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n",
      "WARNING:tensorflow:From C:\\Users\\forwhat\\anaconda3\\envs\\pytorch-gpu\\lib\\site-packages\\tensorflow\\python\\ops\\math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.cast instead.\n",
      "Epoch 1/100\n",
      " - 1s - loss: 0.0789\n",
      "Epoch 2/100\n",
      " - 0s - loss: 0.0725\n",
      "Epoch 3/100\n",
      " - 0s - loss: 0.0664\n",
      "Epoch 4/100\n",
      " - 0s - loss: 0.0606\n",
      "Epoch 5/100\n",
      " - 0s - loss: 0.0549\n",
      "Epoch 6/100\n",
      " - 0s - loss: 0.0495\n",
      "Epoch 7/100\n",
      " - 0s - loss: 0.0442\n",
      "Epoch 8/100\n",
      " - 0s - loss: 0.0392\n",
      "Epoch 9/100\n",
      " - 0s - loss: 0.0343\n",
      "Epoch 10/100\n",
      " - 0s - loss: 0.0296\n",
      "Epoch 11/100\n",
      " - 0s - loss: 0.0251\n",
      "Epoch 12/100\n",
      " - 0s - loss: 0.0209\n",
      "Epoch 13/100\n",
      " - 0s - loss: 0.0169\n",
      "Epoch 14/100\n",
      " - 0s - loss: 0.0132\n",
      "Epoch 15/100\n",
      " - 0s - loss: 0.0098\n",
      "Epoch 16/100\n",
      " - 0s - loss: 0.0068\n",
      "Epoch 17/100\n",
      " - 0s - loss: 0.0043\n",
      "Epoch 18/100\n",
      " - 0s - loss: 0.0024\n",
      "Epoch 19/100\n",
      " - 0s - loss: 0.0011\n",
      "Epoch 20/100\n",
      " - 0s - loss: 4.3149e-04\n",
      "Epoch 21/100\n",
      " - 0s - loss: 4.4403e-04\n",
      "Epoch 22/100\n",
      " - 0s - loss: 0.0010\n",
      "Epoch 23/100\n",
      " - 0s - loss: 0.0019\n",
      "Epoch 24/100\n",
      " - 0s - loss: 0.0029\n",
      "Epoch 25/100\n",
      " - 0s - loss: 0.0037\n",
      "Epoch 26/100\n",
      " - 0s - loss: 0.0040\n",
      "Epoch 27/100\n",
      " - 0s - loss: 0.0040\n",
      "Epoch 28/100\n",
      " - 0s - loss: 0.0036\n",
      "Epoch 29/100\n",
      " - 0s - loss: 0.0030\n",
      "Epoch 30/100\n",
      " - 0s - loss: 0.0023\n",
      "Epoch 31/100\n",
      " - 0s - loss: 0.0016\n",
      "Epoch 32/100\n",
      " - 0s - loss: 9.9590e-04\n",
      "Epoch 33/100\n",
      " - 0s - loss: 5.4428e-04\n",
      "Epoch 34/100\n",
      " - 0s - loss: 2.5068e-04\n",
      "Epoch 35/100\n",
      " - 0s - loss: 1.0307e-04\n",
      "Epoch 36/100\n",
      " - 0s - loss: 7.4385e-05\n",
      "Epoch 37/100\n",
      " - 0s - loss: 1.3087e-04\n",
      "Epoch 38/100\n",
      " - 0s - loss: 2.3833e-04\n",
      "Epoch 39/100\n",
      " - 0s - loss: 3.6622e-04\n",
      "Epoch 40/100\n",
      " - 0s - loss: 4.8995e-04\n",
      "Epoch 41/100\n",
      " - 0s - loss: 5.9170e-04\n",
      "Epoch 42/100\n",
      " - 0s - loss: 6.6030e-04\n",
      "Epoch 43/100\n",
      " - 0s - loss: 6.9063e-04\n",
      "Epoch 44/100\n",
      " - 0s - loss: 6.8264e-04\n",
      "Epoch 45/100\n",
      " - 0s - loss: 6.4029e-04\n",
      "Epoch 46/100\n",
      " - 0s - loss: 5.7050e-04\n",
      "Epoch 47/100\n",
      " - 0s - loss: 4.8202e-04\n",
      "Epoch 48/100\n",
      " - 0s - loss: 3.8444e-04\n",
      "Epoch 49/100\n",
      " - 0s - loss: 2.8722e-04\n",
      "Epoch 50/100\n",
      " - 0s - loss: 1.9879e-04\n",
      "Epoch 51/100\n",
      " - 0s - loss: 1.2582e-04\n",
      "Epoch 52/100\n",
      " - 0s - loss: 7.2661e-05\n",
      "Epoch 53/100\n",
      " - 0s - loss: 4.1027e-05\n",
      "Epoch 54/100\n",
      " - 0s - loss: 2.9959e-05\n",
      "Epoch 55/100\n",
      " - 0s - loss: 3.6146e-05\n",
      "Epoch 56/100\n",
      " - 0s - loss: 5.4538e-05\n",
      "Epoch 57/100\n",
      " - 0s - loss: 7.9186e-05\n",
      "Epoch 58/100\n",
      " - 0s - loss: 1.0418e-04\n",
      "Epoch 59/100\n",
      " - 0s - loss: 1.2454e-04\n",
      "Epoch 60/100\n",
      " - 0s - loss: 1.3683e-04\n",
      "Epoch 61/100\n",
      " - 0s - loss: 1.3952e-04\n",
      "Epoch 62/100\n",
      " - 0s - loss: 1.3291e-04\n",
      "Epoch 63/100\n",
      " - 0s - loss: 1.1882e-04\n",
      "Epoch 64/100\n",
      " - 0s - loss: 9.9997e-05\n",
      "Epoch 65/100\n",
      " - 0s - loss: 7.9507e-05\n",
      "Epoch 66/100\n",
      " - 0s - loss: 6.0179e-05\n",
      "Epoch 67/100\n",
      " - 0s - loss: 4.4188e-05\n",
      "Epoch 68/100\n",
      " - 0s - loss: 3.2833e-05\n",
      "Epoch 69/100\n",
      " - 0s - loss: 2.6498e-05\n",
      "Epoch 70/100\n",
      " - 0s - loss: 2.4776e-05\n",
      "Epoch 71/100\n",
      " - 0s - loss: 2.6680e-05\n",
      "Epoch 72/100\n",
      " - 0s - loss: 3.0903e-05\n",
      "Epoch 73/100\n",
      " - 0s - loss: 3.6071e-05\n",
      "Epoch 74/100\n",
      " - 0s - loss: 4.0956e-05\n",
      "Epoch 75/100\n",
      " - 0s - loss: 4.4620e-05\n",
      "Epoch 76/100\n",
      " - 0s - loss: 4.6500e-05\n",
      "Epoch 77/100\n",
      " - 0s - loss: 4.6421e-05\n",
      "Epoch 78/100\n",
      " - 0s - loss: 4.4548e-05\n",
      "Epoch 79/100\n",
      " - 0s - loss: 4.1304e-05\n",
      "Epoch 80/100\n",
      " - 0s - loss: 3.7267e-05\n",
      "Epoch 81/100\n",
      " - 0s - loss: 3.3053e-05\n",
      "Epoch 82/100\n",
      " - 0s - loss: 2.9219e-05\n",
      "Epoch 83/100\n",
      " - 0s - loss: 2.6182e-05\n",
      "Epoch 84/100\n",
      " - 0s - loss: 2.4180e-05\n",
      "Epoch 85/100\n",
      " - 0s - loss: 2.3252e-05\n",
      "Epoch 86/100\n",
      " - 0s - loss: 2.3268e-05\n",
      "Epoch 87/100\n",
      " - 0s - loss: 2.3971e-05\n",
      "Epoch 88/100\n",
      " - 0s - loss: 2.5040e-05\n",
      "Epoch 89/100\n",
      " - 0s - loss: 2.6150e-05\n",
      "Epoch 90/100\n",
      " - 0s - loss: 2.7033e-05\n",
      "Epoch 91/100\n",
      " - 0s - loss: 2.7510e-05\n",
      "Epoch 92/100\n",
      " - 0s - loss: 2.7508e-05\n",
      "Epoch 93/100\n",
      " - 0s - loss: 2.7057e-05\n",
      "Epoch 94/100\n",
      " - 0s - loss: 2.6263e-05\n",
      "Epoch 95/100\n",
      " - 0s - loss: 2.5281e-05\n",
      "Epoch 96/100\n",
      " - 0s - loss: 2.4273e-05\n",
      "Epoch 97/100\n",
      " - 0s - loss: 2.3382e-05\n",
      "Epoch 98/100\n",
      " - 0s - loss: 2.2706e-05\n",
      "Epoch 99/100\n",
      " - 0s - loss: 2.2290e-05\n",
      "Epoch 100/100\n",
      " - 0s - loss: 2.2127e-05\n",
      "DATA 目录已存在\n",
      "[[[0.10709041]\n",
      "  [0.19697955]\n",
      "  [0.2951117 ]\n",
      "  [0.40231982]]]\n"
     ]
    }
   ],
   "source": [
    "from keras.models import Model\n",
    "from keras.layers import Input\n",
    "from keras.layers import LSTM\n",
    "from numpy import array\n",
    "from keras.models import Sequential\n",
    "from keras.layers import TimeDistributed\n",
    " \n",
    "data = array([0.1,0.2,0.3,0.4]).reshape((1,4,1))\n",
    "model = Sequential()\n",
    "model.add(LSTM(128, input_shape=(data.shape[1], data.shape[2]),return_sequences=True))\n",
    "\n",
    "model.add(TimeDistributed(Dense(1)))\n",
    "\n",
    "model.summary()\n",
    "\n",
    "model.compile(loss='mean_squared_error', optimizer='adam')\n",
    "model.fit(data, data, epochs=100, batch_size=1, verbose=2)\n",
    "# lstm1,state_h,state_c = LSTM(2,return_sequences=True,return_state=True)(inputs1)\n",
    "# lstm2 = LSTM(2,return_sequences=True)(lstm1)\n",
    "# model = Model(input = inputs1,outputs = [lstm2])\n",
    "mkpath=\"DATA\" #保存模型的路径\n",
    "mkdir(mkpath)#创造文件夹\n",
    "model.save(os.path.join(\"DATA\",\"Test\" + \".h5\"))\n",
    "print(model.predict(data))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "_________________________________________________________________\n",
      "Layer (type)                 Output Shape              Param #   \n",
      "=================================================================\n",
      "simple_rnn_1 (SimpleRNN)     (None, 4, 128)            16640     \n",
      "_________________________________________________________________\n",
      "flatten_2 (Flatten)          (None, 512)               0         \n",
      "_________________________________________________________________\n",
      "dense_4 (Dense)              (None, 3)                 1539      \n",
      "_________________________________________________________________\n",
      "reshape_2 (Reshape)          (None, 3, 1)              0         \n",
      "_________________________________________________________________\n",
      "time_distributed_3 (TimeDist (None, 3, 1)              2         \n",
      "=================================================================\n",
      "Total params: 18,181\n",
      "Trainable params: 18,181\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n",
      "Epoch 1/100\n",
      " - 0s - loss: 43.5013\n",
      "Epoch 2/100\n",
      " - 0s - loss: 42.1392\n",
      "Epoch 3/100\n",
      " - 0s - loss: 40.7802\n",
      "Epoch 4/100\n",
      " - 0s - loss: 38.9771\n",
      "Epoch 5/100\n",
      " - 0s - loss: 37.2763\n",
      "Epoch 6/100\n",
      " - 0s - loss: 35.4035\n",
      "Epoch 7/100\n",
      " - 0s - loss: 32.9489\n",
      "Epoch 8/100\n",
      " - 0s - loss: 30.5447\n",
      "Epoch 9/100\n",
      " - 0s - loss: 28.0216\n",
      "Epoch 10/100\n",
      " - 0s - loss: 25.3994\n",
      "Epoch 11/100\n",
      " - 0s - loss: 22.7538\n",
      "Epoch 12/100\n",
      " - 0s - loss: 19.8816\n",
      "Epoch 13/100\n",
      " - 0s - loss: 17.0154\n",
      "Epoch 14/100\n",
      " - 0s - loss: 14.4879\n",
      "Epoch 15/100\n",
      " - 0s - loss: 12.0376\n",
      "Epoch 16/100\n",
      " - 0s - loss: 9.5605\n",
      "Epoch 17/100\n",
      " - 0s - loss: 7.4376\n",
      "Epoch 18/100\n",
      " - 0s - loss: 5.6338\n",
      "Epoch 19/100\n",
      " - 0s - loss: 4.0983\n",
      "Epoch 20/100\n",
      " - 0s - loss: 2.9307\n",
      "Epoch 21/100\n",
      " - 0s - loss: 1.9694\n",
      "Epoch 22/100\n",
      " - 0s - loss: 1.2756\n",
      "Epoch 23/100\n",
      " - 0s - loss: 0.8121\n",
      "Epoch 24/100\n",
      " - 0s - loss: 0.6722\n",
      "Epoch 25/100\n",
      " - 0s - loss: 0.4634\n",
      "Epoch 26/100\n",
      " - 0s - loss: 0.3848\n",
      "Epoch 27/100\n",
      " - 0s - loss: 0.3393\n",
      "Epoch 28/100\n",
      " - 0s - loss: 0.3372\n",
      "Epoch 29/100\n",
      " - 0s - loss: 0.3262\n",
      "Epoch 30/100\n",
      " - 0s - loss: 0.3008\n",
      "Epoch 31/100\n",
      " - 0s - loss: 0.2884\n",
      "Epoch 32/100\n",
      " - 0s - loss: 0.2725\n",
      "Epoch 33/100\n",
      " - 0s - loss: 0.2559\n",
      "Epoch 34/100\n",
      " - 0s - loss: 0.2578\n",
      "Epoch 35/100\n",
      " - 0s - loss: 0.2437\n",
      "Epoch 36/100\n",
      " - 0s - loss: 0.2369\n",
      "Epoch 37/100\n",
      " - 0s - loss: 0.2338\n",
      "Epoch 38/100\n",
      " - 0s - loss: 0.2258\n",
      "Epoch 39/100\n",
      " - 0s - loss: 0.2216\n",
      "Epoch 40/100\n",
      " - 0s - loss: 0.2218\n",
      "Epoch 41/100\n",
      " - 0s - loss: 0.2158\n",
      "Epoch 42/100\n",
      " - 0s - loss: 0.2123\n",
      "Epoch 43/100\n",
      " - 0s - loss: 0.2060\n",
      "Epoch 44/100\n",
      " - 0s - loss: 0.2014\n",
      "Epoch 45/100\n",
      " - 0s - loss: 0.2051\n",
      "Epoch 46/100\n",
      " - 0s - loss: 0.1973\n",
      "Epoch 47/100\n",
      " - 0s - loss: 0.1924\n",
      "Epoch 48/100\n",
      " - 0s - loss: 0.1911\n",
      "Epoch 49/100\n",
      " - 0s - loss: 0.1833\n",
      "Epoch 50/100\n",
      " - 0s - loss: 0.1801\n",
      "Epoch 51/100\n",
      " - 0s - loss: 0.1791\n",
      "Epoch 52/100\n",
      " - 0s - loss: 0.1752\n",
      "Epoch 53/100\n",
      " - 0s - loss: 0.1721\n",
      "Epoch 54/100\n",
      " - 0s - loss: 0.1728\n",
      "Epoch 55/100\n",
      " - 0s - loss: 0.1714\n",
      "Epoch 56/100\n",
      " - 0s - loss: 0.1671\n",
      "Epoch 57/100\n",
      " - 0s - loss: 0.1611\n",
      "Epoch 58/100\n",
      " - 0s - loss: 0.1592\n",
      "Epoch 59/100\n",
      " - 0s - loss: 0.1560\n",
      "Epoch 60/100\n",
      " - 0s - loss: 0.1547\n",
      "Epoch 61/100\n",
      " - 0s - loss: 0.1547\n",
      "Epoch 62/100\n",
      " - 0s - loss: 0.1511\n",
      "Epoch 63/100\n",
      " - 0s - loss: 0.1480\n",
      "Epoch 64/100\n",
      " - 0s - loss: 0.1471\n",
      "Epoch 65/100\n",
      " - 0s - loss: 0.1421\n",
      "Epoch 66/100\n",
      " - 0s - loss: 0.1484\n",
      "Epoch 67/100\n",
      " - 0s - loss: 0.1427\n",
      "Epoch 68/100\n",
      " - 0s - loss: 0.1398\n",
      "Epoch 69/100\n",
      " - 0s - loss: 0.1370\n",
      "Epoch 70/100\n",
      " - 0s - loss: 0.1338\n",
      "Epoch 71/100\n",
      " - 0s - loss: 0.1325\n",
      "Epoch 72/100\n",
      " - 0s - loss: 0.1318\n",
      "Epoch 73/100\n",
      " - 0s - loss: 0.1305\n",
      "Epoch 74/100\n",
      " - 0s - loss: 0.1293\n",
      "Epoch 75/100\n",
      " - 0s - loss: 0.1310\n",
      "Epoch 76/100\n",
      " - 0s - loss: 0.1268\n",
      "Epoch 77/100\n",
      " - 0s - loss: 0.1286\n",
      "Epoch 78/100\n",
      " - 0s - loss: 0.1227\n",
      "Epoch 79/100\n",
      " - 0s - loss: 0.1212\n",
      "Epoch 80/100\n",
      " - 0s - loss: 0.1195\n",
      "Epoch 81/100\n",
      " - 0s - loss: 0.1168\n",
      "Epoch 82/100\n",
      " - 0s - loss: 0.1149\n",
      "Epoch 83/100\n",
      " - 0s - loss: 0.1139\n",
      "Epoch 84/100\n",
      " - 0s - loss: 0.1167\n",
      "Epoch 85/100\n",
      " - 0s - loss: 0.1108\n",
      "Epoch 86/100\n",
      " - 0s - loss: 0.1186\n",
      "Epoch 87/100\n",
      " - 0s - loss: 0.1124\n",
      "Epoch 88/100\n",
      " - 0s - loss: 0.1101\n",
      "Epoch 89/100\n",
      " - 0s - loss: 0.1077\n",
      "Epoch 90/100\n",
      " - 0s - loss: 0.1061\n",
      "Epoch 91/100\n",
      " - 0s - loss: 0.1043\n",
      "Epoch 92/100\n",
      " - 0s - loss: 0.1043\n",
      "Epoch 93/100\n",
      " - 0s - loss: 0.1027\n",
      "Epoch 94/100\n",
      " - 0s - loss: 0.1011\n",
      "Epoch 95/100\n",
      " - 0s - loss: 0.0997\n",
      "Epoch 96/100\n",
      " - 0s - loss: 0.0993\n",
      "Epoch 97/100\n",
      " - 0s - loss: 0.0996\n",
      "Epoch 98/100\n",
      " - 0s - loss: 0.0978\n",
      "Epoch 99/100\n",
      " - 0s - loss: 0.0988\n",
      "Epoch 100/100\n",
      " - 0s - loss: 0.0962\n",
      "DATA 目录已存在\n"
     ]
    }
   ],
   "source": [
    "from keras.layers.core import Reshape\n",
    "from keras.layers.core import Flatten\n",
    "from keras.layers import TimeDistributed\n",
    "from keras.layers import SimpleRNN\n",
    "# create and fit the LSTM network\n",
    "model = Sequential()\n",
    "'''\n",
    "keras中SimpleRNN层的计算流程验证\n",
    "https://www.jianshu.com/p/d214ae0432b0\n",
    "'''\n",
    "\n",
    "# model.add(LSTM(128, input_shape=(train_x.shape[1], train_x.shape[2]),return_sequences=True))\n",
    "model.add(SimpleRNN(512,input_shape=(train_x.shape[1], train_x.shape[2]),return_sequences=True))\n",
    "model.add(Flatten())\n",
    "model.add(Dense(3))\n",
    "model.add(Reshape((3, 1)))\n",
    "model.add(TimeDistributed(Dense(1)))\n",
    "#Dense\n",
    "model.summary()\n",
    "model.compile(loss='mean_squared_error', optimizer='adam')\n",
    "model.fit(train_x, train_y, epochs=100, batch_size=1, verbose=2)\n",
    "\n",
    "mkpath=\"DATA\" #保存模型的路径\n",
    "mkdir(mkpath)#创造文件夹\n",
    "model.save(os.path.join(\"DATA\",\"Test\" + \".h5\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[0.]\n",
      "  [1.]\n",
      "  [2.]\n",
      "  [3.]]\n",
      "\n",
      " [[1.]\n",
      "  [2.]\n",
      "  [3.]\n",
      "  [4.]]\n",
      "\n",
      " [[2.]\n",
      "  [3.]\n",
      "  [4.]\n",
      "  [5.]]\n",
      "\n",
      " [[3.]\n",
      "  [4.]\n",
      "  [5.]\n",
      "  [6.]]]\n",
      "===================\n",
      "[[1.]\n",
      " [2.]\n",
      " [3.]\n",
      " [4.]]\n",
      "===================\n",
      "===================\n",
      "[[[5.331096 ]\n",
      "  [6.3880825]\n",
      "  [7.3890166]]]\n",
      "===================\n",
      "[[[3.9663196]\n",
      "  [4.869606 ]\n",
      "  [5.7311435]]\n",
      "\n",
      " [[5.331096 ]\n",
      "  [6.388082 ]\n",
      "  [7.389016 ]]\n",
      "\n",
      " [[6.081065 ]\n",
      "  [7.1071553]\n",
      "  [8.142271 ]]\n",
      "\n",
      " [[6.5551424]\n",
      "  [7.5383964]\n",
      "  [8.597859 ]]]\n"
     ]
    }
   ],
   "source": [
    "print(train_x)\n",
    "print(\"===================\")\n",
    "# print(train_x[0])\n",
    "print(train_x[1])\n",
    "print(\"===================\")\n",
    "predict_x = train_x[1].reshape(1, train_x.shape[1], 1)#shape=(1,seq_length,dim) sample=1 很好理解\n",
    "print(\"===================\")\n",
    "y_train_pred_nn = model.predict(predict_x)\n",
    "print(y_train_pred_nn)\n",
    "print(\"===================\")\n",
    "y_train_pred_all = model.predict(train_x)#预测序列\n",
    "print(y_train_pred_all)"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "ea70d47c1026074199160e48050b9f1be75d4ba7d6f2081b88238ca77789226b"
  },
  "kernelspec": {
   "display_name": "Python 3.7.11 ('pytorch-gpu')",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.11"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
